package loan.calc.service.loan.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import loan.calc.domain.LoanDO;
import loan.calc.dto.LoanDTO;
import loan.calc.mapper.LoanMapper;
import loan.calc.service.loan.LoanRateSegmentService;
import loan.calc.service.loan.LoanRepayScheduleService;
import loan.calc.service.loan.LoanRepaySegmentService;
import loan.calc.service.loan.LoanService;
import loan.calc.util.POJOConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class LoanServiceImpl extends ServiceImpl<LoanMapper, LoanDO> implements LoanService {

    private final LoanRateSegmentService loanRateSegmentService;

    private final LoanRepaySegmentService loanRepaySegmentService;

    private final LoanRepayScheduleService loanRepayScheduleService;

    @Override
    public void setLoanId(LoanDTO loan, Long loanId) {
        loan.setLoanId(loanId);
        if (loan.getLoanRateSegmentList() != null && loan.getLoanRateSegmentList().size() > 0) {
            loan.getLoanRateSegmentList().forEach(i -> i.setLoanId(loanId));
        }
        if (loan.getLoanRepaySegmentList() != null && loan.getLoanRepaySegmentList().size() > 0) {
            loan.getLoanRepaySegmentList().forEach(i -> i.setLoanId(loanId));
        }
        if (loan.getRepayScheduleList() != null && loan.getRepayScheduleList().size() > 0) {
            loan.getRepayScheduleList().forEach(i -> i.setLoanId(loanId));
        }
    }

    @Override
    public LoanDTO getFull(Long loanId) {
        LoanDO loanDO = getById(loanId);
        LoanDTO loan = POJOConverter.convert(LoanDTO.class, loanDO);
        loan.setLoanRateSegmentList(loanRateSegmentService.getLoanRateSegmentList(loan.getLoanId()));
        loan.setLoanRepaySegmentList(loanRepaySegmentService.getLoanRepaySegmentListByLoanId(loan.getLoanId()));
        loan.setRepayScheduleList(loanRepayScheduleService.getRepayScheduleListByLoanId(loan.getLoanId()));
        return loan;
    }

    @Override
    public List<LoanDTO> getFullAll() {
        return lambdaQuery().select(LoanDO::getLoanId)
                .list().stream().map(loanDO -> getFull(loanDO.getLoanId()))
                .collect(Collectors.toList());

    }

}
